package com.hisoft.web.view.report;

import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import org.apache.struts2.views.util.ResourceUtil;

import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;

public class PdfReportResult extends StrutsResultSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8048928657518073762L;

	protected ActionInvocation invocation;

	protected String location;
	@SuppressWarnings("unchecked")
	@Override
	protected void doExecute(String location, ActionInvocation invocation) throws Exception {
		this.location = location;
		this.invocation = invocation;

		if (!location.startsWith("/")) {
			ActionContext ctx = invocation.getInvocationContext();
			HttpServletRequest req = (HttpServletRequest) ctx
					.get(ServletActionContext.HTTP_REQUEST);
			String base = ResourceUtil.getResourceBase(req);
			location = base + "/" + location;
		} else {
			String contextpath = ServletActionContext.getServletContext()
					.getRealPath("/");
			location = contextpath + "/" + location;
		}
		
		//
		ITextMaper<Object,ITextField> maper = (ITextMaper<Object,ITextField>) invocation.getStack().findValue("maper");
		if (null == maper)
			throw new Exception("maper is null.");
		
		Object fieldData = invocation.getStack().findValue("fieldData");
		if (null == fieldData)
			throw new Exception("fieldData is null.");
		
		//
		
		
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		//
		PdfReader reader = new PdfReader(location);
		PdfStamper stamp = new PdfStamper(reader, baos);
		
		AcroFields form = stamp.getAcroFields();
		
		Iterator it = ((Map)form.getFields()).entrySet().iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
		
		ITextField itext = new ITextField(form);
		maper.mapRow(fieldData,itext);
		
		stamp.setFormFlattening(true);
		
		stamp.close();
		reader.close();
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Expires", "0");
		response.setHeader("Cache-Control",
				"must-revalidate, post-check=0, pre-check=0");
		response.setHeader("Pragma", "public");
		response.setContentType("application/pdf");
		response.setHeader("Content-Disposition", "inline;Filename="
				+ System.currentTimeMillis() + ".pdf");
		
		ServletOutputStream out = response.getOutputStream();
		baos.writeTo(out);
		baos.close();
		out.flush();
		out.close();
		
	}

}
